package com.sneakxy.cloudbase.platform.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import com.alibaba.cloud.seata.rest.SeataRestTemplateInterceptor;

/**
 * 解决SeataRestTemplateAutoConfiguration循环依赖问题
 * @author 潜行的虚影
 *
 */
@Configuration(proxyBeanMethods = false)
public class CloudBaseSeataRestTemplateAutoConfiguration {

	@Bean
	public SeataRestTemplateInterceptor seataRestTemplateInterceptor() {
		return new SeataRestTemplateInterceptor();
	}

	@Autowired(required = false)
	private Collection<RestTemplate> restTemplates;

	@PostConstruct
	public void init() {
		if (this.restTemplates != null) {
			for (RestTemplate restTemplate : restTemplates) {
				List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
						restTemplate.getInterceptors());
				interceptors.add(seataRestTemplateInterceptor());
				restTemplate.setInterceptors(interceptors);
			}
		}
	}
	
}
